package com.example.hotel_lxy.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.EventBusBean;
import com.example.hotel_lxy.bean.ImgBean;
import com.example.hotel_lxy.bean.ReturnVisitBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.dialog.ImageViewpagerDialog;
import com.example.hotel_lxy.ui.main.CalendarActivity;
import com.example.hotel_lxy.utils.GlideEngine;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.ysxsoft.common_base.view.custom.image.RoundImageView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 回访
 */
@Route(path = "/main/ReturnVisitActivity")
public class ReturnVisitActivity extends BaseActivity {

    @BindView(R.id.rv_return_img)
    RecyclerView rvReturnImg;
    @BindView(R.id.rv_speed_of)
    RecyclerView rvSpeedOf;

    @Autowired
    String id;
    @Autowired
    String user_id;
    @BindView(R.id.add_Returnvisit)
    TextView addReturnvisit;
    @BindView(R.id.text_time)
    TextView textTime;
    @BindView(R.id.text_content)
    EditText textContent;
    @BindView(R.id.rb1)
    RadioButton rb1;
    @BindView(R.id.rb2)
    RadioButton rb2;
    @BindView(R.id.rb3)
    RadioButton rb3;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.line1)
    LinearLayout line1;
    private String otherl = "";
    private List<String> mlist = new ArrayList<>();


    public static void start(String id,String user_id) {
        ARouter.getInstance().build(ARouterPath.getReturnVisitActivity())
                .withString("id", id)
                .withString("user_id",user_id)
                .navigation();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_return_visit;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void doWork() {
        ARouter.getInstance().inject(this);
        EventBus.getDefault().register(this);  //事件的注册
        super.doWork();
        rb1.setChecked(true);
        showDataSpeedOf();
        showRVImg();
        addReturnvisit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean addvisit = JurisdictionUtils.getAddvisit(ReturnVisitActivity.this);
                if (!addvisit) {
                    boolean getuserid = JurisdictionUtils.getuserid(ReturnVisitActivity.this, user_id);
                    if (!getuserid) {
                        ToastUtils.longToast(ReturnVisitActivity.this, "当前账号没有操作权限哦");
                        return;
                    }
                }
                if(textTime.getText().toString().equals("")){
                    ToastUtils.shortToast(ReturnVisitActivity.this,"请选择回访时间");
                    return;
                }
                if(textContent.getText().toString().equals("")){
                    ToastUtils.shortToast(ReturnVisitActivity.this,"请填写回访内容");
                    return;
                }
                if(mlist.size()>0){
                    if ((mlist.size() - 1) == 0) {
                        showAddDate();
                    } else {
                        showImgview();
                    }
                }else{
                    showAddDate();
                }
            }
        });
        textTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CalendarActivity.start(4);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        line1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textContent.setFocusable(true);
                textContent.setFocusableInTouchMode(true);
                textContent.requestFocus();
                initInput();
            }
        });
    }
    private void initInput() {
        InputMethodManager inputManager = (InputMethodManager)textContent.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(textContent, 0);
    }
    private void showImgview() {
        if(mlist.size()>0){
            mlist.remove(0);
        }
        PostFormBuilder builder = OkHttpUtils.post()
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .url(Api.POSY_UPLOADS);
        for (int i = 0; i < mlist.size(); i++) {
            String path = mlist.get(i);
            if (path != null && !path.isEmpty()) {
                File file = new File(path);
                builder.addFile("file[]", file.getName(), file);
            }
        }
        showLoadingDialog();
        builder.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                Log.e("TAG", "合同图片onResponse~~~~~~~~    " + response);
                ImgBean imgBean = JsonUtils.parseByGson(response, ImgBean.class);
                StringBuffer sb = new StringBuffer();
                if (imgBean.getCode().equals("0")) {
                    for (int i = 0; i < imgBean.getData().size(); i++) {
                        ImgBean.DataBean dataBean = imgBean.getData().get(i);
                        sb.append(dataBean.getId() + ",");
                    }
                    otherl = sb.toString();
                    showAddDate();
                }
            }
        });
    }

    private void showAddDate() {
        int type = 1;
        if (rb1.isChecked()) {
            type = 1;
        } else if (rb2.isChecked()) {
            type = 2;
        } else if (rb3.isChecked()) {
            type = 3;
        }
        String token = SPUtils.get(ReturnVisitActivity.this, "token", "").toString();
        OkHttpUtils.post()
                .url(Api.POST_HISTIRY_SAVE)
                .addHeader("flag", token)
                .addParams("id", id)
                .addParams("time", textTime.getText().toString())
                .addParams("content", textContent.getText().toString())
                .addParams("other", "" + otherl)
                .addParams("type", type + "")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "添加回访onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "添加回访onResponse   " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("0")) {
                            textTime.setText("");
                            textContent.setText("");
                            mlist.clear();
                            showRVImg();
                            showDataSpeedOf();
                        } else if (beanBean.getCode().equals("4")) {
                            SPUtils.put(ReturnVisitActivity.this, "token", "");
                            Intent intent = new Intent(ReturnVisitActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }

                    }
                });
    }


    private void showRVImg() {
        if(mlist.size()!=20){
            mlist.add(0, "");
        }
        rvReturnImg.setLayoutManager(new GridLayoutManager(ReturnVisitActivity.this, 3));
        RBaseAdapter<String> rBaseAdapter = new RBaseAdapter<String>(ReturnVisitActivity.this, R.layout.item_returnvist_img, mlist) {
            @Override
            protected void fillItem(RViewHolder holder, String item, int position) {
                RoundImageView img = holder.itemView.findViewById(R.id.img_round);
                ImageView img_detele = holder.itemView.findViewById(R.id.img_detele);
                if (!item.equals("")) {
                    img_detele.setVisibility(View.VISIBLE);
                    Glide.with(ReturnVisitActivity.this).load(item).into(img);
                } else {
                    img_detele.setVisibility(View.GONE);
                    Glide.with(ReturnVisitActivity.this).load(R.mipmap.icon_rv_img).into(img);
                }
                img_detele.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mlist.remove(position);
                        if (mlist.size() < 20) {
                            if (!mlist.contains("")) {
                                mlist.add(0, "");
                            }
                        }
                        notifyDataSetChanged();
                    }
                });
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (item.equals("")) {
                            showImg();
                        }else{
                            if(mlist.size()!=20){
                                ImageViewpagerDialog.show(ReturnVisitActivity.this, null, mlist, position-1);
                            }else{
                                ImageViewpagerDialog.show(ReturnVisitActivity.this, null, mlist, position);
                            }

                        }
                    }
                });
            }

            @Override
            protected int getViewType(String item, int position) {
                return 0;
            }
        };
        rvReturnImg.setAdapter(rBaseAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
            if (localMedia != null) {
                if(mlist.size()!=0){
                    if(mlist.get(0).equals("")){
                        mlist.remove(0);
                    }
                }
                for (int i = 0; i < localMedia.size(); i++) {
                    mlist.add(localMedia.get(i).getCompressPath());
                }
                showRVImg();
            }
        }
    }

    private void showImg() {
        if(mlist.size()>0){
            if(mlist.get(0).equals("")){
                mlist.remove(0);
            }
        }

        int j=20-Integer.valueOf(mlist.size());
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .selectionMode(100)
                .maxSelectNum(j)
                .previewImage(true)
                .compress(true)//图片是否压缩
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    private void showDataSpeedOf() {
        String token = SPUtils.get(ReturnVisitActivity.this, "token", "").toString();
        OkHttpUtils.post()
                .url(Api.POST_HISTORY)
                .addHeader("flag", token)
                .addParams("id", id)
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "营销首页onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "回访onResponse   " + response);

                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if (beanBean.getCode().equals("4")) {
                            SPUtils.put(ReturnVisitActivity.this, "token", "");
                            Intent intent = new Intent(ReturnVisitActivity.this, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        if (beanBean.getCode().equals("0")) {
                            ReturnVisitBean returnVisitBean = JsonUtils.parseByGson(response, ReturnVisitBean.class);
                            rvSpeedOf.setLayoutManager(new LinearLayoutManager(ReturnVisitActivity.this));
                            RBaseAdapter<ReturnVisitBean.DataBean.ListBean> rBaseAdapter = new RBaseAdapter<ReturnVisitBean.DataBean.ListBean>(ReturnVisitActivity.this,
                                    R.layout.item_return_speed_activity, returnVisitBean.getData().getList()) {
                                @Override
                                protected void fillItem(RViewHolder holder, ReturnVisitBean.DataBean.ListBean item, int position) {
                                    TextView text_number = holder.itemView.findViewById(R.id.text_number);
                                    TextView text_addtime_manager = holder.itemView.findViewById(R.id.text_addtime_manager);
                                    TextView text_type = holder.itemView.findViewById(R.id.text_type);
                                    TextView text_content = holder.itemView.findViewById(R.id.text_content);
                                    RecyclerView rv_speed_list = holder.itemView.findViewById(R.id.rv_speed_list);
                                    if (item.getType() == 1) {
                                        text_type.setText("方式：电话");
                                    } else if (item.getType() == 2) {
                                        text_type.setText("方式：微信");
                                    } else if (item.getType() == 3) {
                                        text_type.setText("方式：面谈");
                                    }
                                    text_addtime_manager.setText("时间：" + item.getAddtime() + " 跟进员： " + item.getManager());
                                    int size = returnVisitBean.getData().getList().size();
                                    int i = size - position;
                                    text_number.setText("" + i);
                                    text_content.setText("跟进内容：" + item.getContent());
                                    List<String> image = item.getImage();
                                    rv_speed_list.setLayoutManager(new GridLayoutManager(ReturnVisitActivity.this, 3));
                                    RBaseAdapter<String> rBaseAdapter1 = new RBaseAdapter<String>(ReturnVisitActivity.this,
                                            R.layout.item_item_img, item.getImage()) {
                                        @Override
                                        protected void fillItem(RViewHolder holder, String item, int position) {
                                            ImageView img = holder.itemView.findViewById(R.id.img);

                                            Glide.with(ReturnVisitActivity.this).load(item).into(img);
                                            holder.itemView.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    ImageViewpagerDialog.show(ReturnVisitActivity.this, null, image, position);
                                                }
                                            });
                                        }

                                        @Override
                                        protected int getViewType(String item, int position) {
                                            return 0;
                                        }
                                    };
                                    rv_speed_list.setAdapter(rBaseAdapter1);
                                }

                                @Override
                                protected int getViewType(ReturnVisitBean.DataBean.ListBean item, int position) {
                                    return 0;
                                }
                            };
                            rvSpeedOf.setAdapter(rBaseAdapter);
                        }
                    }
                });


    }

    // 普通事件的处理
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleEvent(EventBusBean carrier) {
        if (carrier != null) {
            textTime.setText(carrier.getStarttime());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); //解除注册
    }
}